from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

class CustomUserManager(BaseUserManager):
    def create_user(self, email, username, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email field must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, username, password, **extra_fields)

    def get_by_natural_key(self, email):
        return self.get(email=email)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    # 添加自定义字段
    email = models.EmailField(unique=True, verbose_name='邮箱')
    username = models.CharField(max_length=150, unique=True, verbose_name='用户名')  # 添加用户名字段
    is_admin = models.BooleanField(default=False, verbose_name='是否管理员')  # 添加管理员区分字段
    
    # 指定用户名字段（默认为 username）
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']  # 必填字段

    objects = CustomUserManager()

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
    
        
    def __str__(self):
        return self.email

class Profile(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='profile')
    phone = models.CharField(max_length=15, unique=True, verbose_name='手机号',null=True, blank=True)
    is_verified = models.BooleanField(default=False, verbose_name='是否认证')
    register_time = models.DateTimeField(auto_now_add=True, verbose_name='注册时间')
    last_login_ip = models.GenericIPAddressField(null=True, blank=True, verbose_name='最后登录IP')
    user_type = models.CharField(max_length=10, choices=[('school', '学校'), ('enterprise', '企业')], verbose_name='用户类型')
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, verbose_name='头像')  # 添加头像字段

    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.user.email} - {self.user_type}"